package org.iks.gfs.business.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.iks.gfs.business.entity.GfsChunkFileEntity;
import org.iks.gfs.business.entity.GfsFileEntity;
import org.iks.gfs.business.mapper.GfsChunkFileMapper;
import org.iks.gfs.business.mapper.GfsFileMapper;
import org.iks.gfs.business.service.GfsFileService;
import org.iks.gfs.business.vo.GfsFileVo;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * Author kzou
 * Date 2024/4/6
 * Description:
 */
@Service
public class GfsFileServiceImpl extends ServiceImpl<GfsFileMapper, GfsFileEntity> implements GfsFileService {

    private final GfsChunkFileMapper chunkFileMapper;

    public GfsFileServiceImpl(GfsChunkFileMapper chunkFileMapper) {
        this.chunkFileMapper = chunkFileMapper;
    }

    @Override
    public GfsFileVo queryGfsFile(String gfsFileName) {
        LambdaQueryWrapper<GfsFileEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(GfsFileEntity::getFileName, gfsFileName);
        GfsFileEntity gfsFileEntity = baseMapper.selectOne(queryWrapper);
        if (gfsFileEntity == null) {
            return null;
        }
        List<GfsChunkFileEntity> gfsChunkFiles = chunkFileMapper.queryFileChunkFiles(gfsFileEntity.getId());
        return new GfsFileVo(gfsFileEntity, gfsChunkFiles);
    }

    @Override
    public GfsFileVo queryGfsFileById(Integer id) {
        GfsFileEntity gfsFileEntity = baseMapper.selectById(id);
        if (gfsFileEntity == null) {
            return null;
        }
        List<GfsChunkFileEntity> gfsChunkFiles = chunkFileMapper.queryFileChunkFiles(gfsFileEntity.getId());
        return new GfsFileVo(gfsFileEntity, gfsChunkFiles);
    }

    @Override
    public int saveChunkFile(String chunkName, Integer chunkIndex, Integer fileId) {
        GfsChunkFileEntity gfsChunkFileEntity = new GfsChunkFileEntity();
        gfsChunkFileEntity.setChunkName(chunkName);
        gfsChunkFileEntity.setChunkIndex(chunkIndex);
        gfsChunkFileEntity.setFileId(fileId);
        gfsChunkFileEntity.setCreateTime(new Date());
        return chunkFileMapper.insert(gfsChunkFileEntity);
    }

    @Override
    public int saveGfsFile(String originalFilename, String gfsFileName) {
        GfsFileEntity gfsFileEntity = new GfsFileEntity();
        gfsFileEntity.setFileName(gfsFileName);
        gfsFileEntity.setOriginalFilename(originalFilename);
        gfsFileEntity.setCreateTime(new Date());
        return baseMapper.insert(gfsFileEntity);
    }

}
